<template>
  <div>
    <el-form label-position="left" label-width="100px" style="width:80%">
      <el-form-item label="原密码："><el-input v-model="formData.passwordOld" placeholder="请输入原密码" class="filter-item" show-password maxlength="18" /></el-form-item>
      <el-form-item label="新密码："><el-input v-model="formData.password" placeholder="请输入新密码" class="filter-item" show-password maxlength="18" /></el-form-item>
      <el-form-item label="确认密码："><el-input v-model="formData.confirmPwd" placeholder="请再次输入新密码" class="filter-item" show-password maxlength="18" /></el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button icon="el-icon-close" @click="cancel">取消</el-button>
      <el-button v-waves :loading="confirmLoading" type="primary" icon="el-icon-check" @click="submit">确定</el-button>
    </div>
  </div>
</template>
<script>
import { changePwd } from '@/api/user';
import waves from '@/directive/waves';

export default {
  name: 'ChangePassword',
  directives: { waves },
  data() {
    return {
      confirmLoading: false,
      formData: {
        oldPwd: '',
        newPwd: '',
        confirmPwd: ''
      }
    };
  },
  created() {},
  methods: {
    async submit() {
      const regExp = /^\w+$/;
      if (this.formData.passwordOld === '') {
        this.$message.error('请输入原密码');
        return;
      }
      if (this.formData.passwordOld.length < 4) {
        this.$message.error('原密码的长度不能小于6位');
        return;
      }
      if (!regExp.test(this.formData.passwordOld)) {
        this.$message.error('原密码只能为英文数字及符号组成');
        return;
      }
      if (this.formData.password === '') {
        this.$message.error('请输入新密码');
        return;
      }
      if (this.formData.password.length < 6) {
        this.$message.error('新密码的长度不能小于6位');
        return;
      }
      if (!regExp.test(this.formData.password)) {
        this.$message.error('新密码只能为英文数字及符号组成');
        return;
      }
      if (this.formData.confirmPwd === '') {
        this.$message.error('请再次输入新密码');
        return;
      }
      if (this.formData.confirmPwd !== this.formData.password) {
        this.$message.error('两次输入的密码不一致');
        return;
      }
      this.confirmLoading = true;
      await changePwd(this.formData).then(res => {
        this.confirmLoading = false;
        if (res.msg !== 'OK') {
          this.$message.error(res.msg);
          return;
        }
        this.$emit('cancelClose', true);
      });
    },
    cancel() {
      this.$emit('cancelClose', false);
    }
  }
};
</script>
